//
//  ByProductSkuCollectionView.m
//  hutouben_ios
//
//  Created by pro on 16/11/30.
//  Copyright © 2016年 mc. All rights reserved.
//

#import "ByViewDetailSkuCollection.h"

@interface ByViewDetailSkuCollection ()

@property (nonatomic, strong) UIScrollView *scroll;

@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *countLabel;

@end

@implementation ByViewDetailSkuCollection
{
    UILabel     *_countModifyLabel;     // 数量视图（可修改）
    UIButton    *_countAddBtn;          // 数量视图（+）
    UIButton    *_countDeleteBtn;       // 数量视图（-）
}
#pragma mark - 懒加载
- (UIScrollView *)scroll {
    
    if (!_scroll) {
        _scroll = [[UIScrollView alloc] init];
        _scroll.backgroundColor = [UIColor whiteColor];
        [self addSubview:_scroll];
        [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return _scroll;
}

- (UILabel *)countLabel {
    
    if (!_countLabel) {
        _countLabel = [[UILabel alloc] init];
        _countLabel.userInteractionEnabled = YES;
        _countLabel.font = FONT(14);
        _countLabel.text = @"1";
        _countLabel.textColor = [UIColor blackColor];
        _countLabel.textAlignment = NSTextAlignmentCenter;
        _countLabel.layer.cornerRadius = 4;
        _countLabel.layer.borderColor = BY_LINE_COLOR.CGColor;
        _countLabel.layer.borderWidth = 1;
    }
    return _countLabel;
}
- (UILabel *)priceLabel {
    
    if (!_priceLabel) {
        _priceLabel = [[UILabel alloc] init];
        _priceLabel.userInteractionEnabled = YES;
        _priceLabel.font = FONT(16);
        _priceLabel.text = @"￥0.00";
        _priceLabel.textColor = BY_THEME_COLOR;
        _priceLabel.textAlignment = NSTextAlignmentRight;
    }
    return _priceLabel;
}

#pragma mark - init
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

- (void)setDataSource:(id<ByProductSkuCollectionViewDataSource>)dataSource {
    
    _dataSource = dataSource;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self reloadData];
    });
}
- (void)setupUI {
    
    CGFloat x, y, width, height;
    CGFloat margin = 10;
    // 总组数
    NSInteger sections = [self.dataSource numOfSections:self];
    
    for (int section = 0; section < sections; section ++) {
        
        // 该组的元素数
        NSInteger items = [self.dataSource numOfItems:self inSection:section];
    
        x = 0;
        y = 0;
        width = self.scroll.width;
        height = 0;
        
        UIView *basaelView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        basaelView.top = self.scroll.subviews.lastObject.bottom;
        [self.scroll addSubview:basaelView];
        
        // 如果有实现标题代理，则创建标题视图
        BOOL hasTitle = NO;
        if ([self.dataSource respondsToSelector:@selector(collectionView:titleInSection:)]) {
            
            hasTitle = YES;
            
            NSString *title = [self.dataSource collectionView:self titleInSection:section];
            width = basaelView.width;
            height = 30;
            x = margin;
            y = 0;
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
            titleLabel.adjustsFontSizeToFitWidth = YES;
            titleLabel.font = FONT(16);
            titleLabel.text = title;
            titleLabel.textColor = [UIColor lightGrayColor];
            titleLabel.textAlignment = NSTextAlignmentLeft;
            [basaelView addSubview:titleLabel];
        }
        
        CGFloat line = 0;
        CGFloat xOffset = margin;
        for (int item = 0; item < items; item ++) {
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:section];
            CGSize size = [self.dataSource collectionView:self sizeForviewAtIndexPath:indexPath];
            UIView *view = [self.dataSource collectionView:self viewAtIndexPath:indexPath];
            width = size.width;
            height = size.height;
            
            // 需要换行了
            if (xOffset + width > basaelView.width - margin) {
                xOffset = margin;
                line ++;
            }
            y = (hasTitle ? 35 : 0) + (height + margin) * line;
        
            // 设置frame
            view.frame = CGRectMake(xOffset, y, width, height);
            [basaelView addSubview:view];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [view addGestureRecognizer:tap];
            view.tag = section * 100 + item * 10;
            
            xOffset += (width + margin);
        }
        
        basaelView.height = basaelView.subviews.lastObject.bottom + margin + 5;
        
        // 线
        x = 10;
        y = basaelView.height - 1;
        width = self.scroll.width - 20;
        height = 1;
        UIView *sepView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        sepView.backgroundColor = BY_LINE_COLOR;
        [basaelView addSubview:sepView];
    }
    
    
    // 创建数量视图
    x = 10;
    y = self.scroll.subviews.lastObject.bottom + 10;
    width = 120;
    height = 30;
    UILabel *countTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    countTitleLabel.font = FONT(16);
    countTitleLabel.text = @"购买数量";
    countTitleLabel.textColor = [UIColor lightGrayColor];
    countTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self.scroll addSubview:countTitleLabel];
    
    
    // 创建数量修改视图
    _countModifyLabel = [[UILabel alloc] init];
    _countModifyLabel.backgroundColor = [UIColor whiteColor];
    _countModifyLabel.userInteractionEnabled = true;
    _countModifyLabel.font = FONT(16);
    _countModifyLabel.text = @"1";
    _countModifyLabel.textColor = [UIColor blackColor];
    _countModifyLabel.textAlignment = NSTextAlignmentCenter;
    _countModifyLabel.layer.borderColor = BY_LINE_COLOR.CGColor;
    _countModifyLabel.layer.borderWidth = 1;
    _countModifyLabel.layer.masksToBounds = true;
    _countModifyLabel.layer.cornerRadius = 15;
    [self.scroll addSubview:_countModifyLabel];
    _countModifyLabel.frame = CGRectMake(0, 0, 120, 30);
    _countModifyLabel.right = self.scroll.width - 10;
    _countModifyLabel.top = countTitleLabel.top;
    
    // 线条
    UIView *line1 = [UIView new];
    line1.backgroundColor = BY_LINE_COLOR;
    [_countModifyLabel addSubview:line1];
    line1.frame = CGRectMake(0, 0, 1, _countModifyLabel.height * 0.65);
    line1.y = _countModifyLabel.height / 2;
    line1.x = _countModifyLabel.width / 3;
    UIView *line2 = [UIView new];
    line2.backgroundColor = BY_LINE_COLOR;
    [_countModifyLabel addSubview:line2];
    line2.frame = CGRectMake(0, 0, 1, _countModifyLabel.height * 0.65);
    line2.y = _countModifyLabel.height / 2;
    line2.x = _countModifyLabel.width / 3 * 2;
    
    _countDeleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _countDeleteBtn.titleLabel.font = FONT(25);
    [_countDeleteBtn setTitle:@"-" forState:UIControlStateNormal];
    [_countDeleteBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_countDeleteBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [_countDeleteBtn addTarget:self action:@selector(countDelete) forControlEvents:UIControlEventTouchUpInside];
    [_countModifyLabel addSubview:_countDeleteBtn];
    _countDeleteBtn.enabled = false;
    _countDeleteBtn.frame = CGRectMake(0, 0, _countModifyLabel.width / 3, _countModifyLabel.height);
    
    _countAddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _countAddBtn.titleLabel.font = FONT(25);
    [_countAddBtn setTitle:@"+" forState:UIControlStateNormal];
    [_countAddBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_countAddBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [_countAddBtn addTarget:self action:@selector(countAdd) forControlEvents:UIControlEventTouchUpInside];
    [_countModifyLabel addSubview:_countAddBtn];
    _countAddBtn.frame = CGRectMake(0, 0, _countModifyLabel.width / 3, _countModifyLabel.height);
    _countAddBtn.right = _countModifyLabel.width;
    
    
    self.scroll.contentSize = CGSizeMake(0, self.scroll.subviews.lastObject.bottom + 10);
}
- (void)countAdd {
    
    int count = _countModifyLabel.text.intValue;
    count ++;
    _countModifyLabel.text = [NSString stringWithFormat:@"%i", count];
    
    
    _countDeleteBtn.enabled = !(count == 1);
    
    if ([self.dataSource respondsToSelector:@selector(collectionView:didModifyCount:)]) {
        
        [self.dataSource collectionView:self didModifyCount:^NSInteger{
            
            return count;
        }];
    }
    
}
- (void)countDelete {
    
    int count = _countModifyLabel.text.intValue;
    if (count == 1) {
        [ByCoreToolAlert showOnlyText:@"已经不能再少了!"];
        return;
    }
    
    count --;
    _countModifyLabel.text = [NSString stringWithFormat:@"%i", count];

    
    // 如果数量为1，-按钮设为无法点击
    _countDeleteBtn.enabled = !(count == 1);
    
    if ([self.dataSource respondsToSelector:@selector(collectionView:didModifyCount:)]) {
        
        [self.dataSource collectionView:self didModifyCount:^NSInteger{
            
            return count;
        }];
    }
}

- (void)delete {
    
    NSString *countStr = self.countLabel.text;
    NSInteger count = countStr.integerValue;
    NSString *newCountStr = [NSString stringWithFormat:@"%li", --count];
    self.countLabel.text = newCountStr;
    
    UIButton *deleteBtn = [self.countLabel viewWithTag:100];
    deleteBtn.enabled = count != 1;
    
    if ([self.dataSource respondsToSelector:@selector(collectionView:didModifyCount:)]) {
        
        [self.dataSource collectionView:self didModifyCount:^NSInteger{
            
            return count;
        }];
    }
}
- (void)add {
    
    NSString *countStr = self.countLabel.text;
    NSInteger count = countStr.integerValue;
    NSString *newCountStr = [NSString stringWithFormat:@"%li", ++count];
    self.countLabel.text = newCountStr;
    
    UIButton *deleteBtn = [self.countLabel viewWithTag:100];
    deleteBtn.enabled = count != 1;
    
    if ([self.dataSource respondsToSelector:@selector(collectionView:didModifyCount:)]) {
        
        [self.dataSource collectionView:self didModifyCount:^NSInteger{
            
            return count;
        }];
    }
}
- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    NSInteger tag = tap.view.tag;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:(tag % 100) / 10 inSection:tag / 100];
    [self.dataSource collectionView:self didSelectItemAtIndexPath:indexPath];
}

- (void)reloadData {
    
    [self.scroll.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self setupUI];
}
@end
